<template>
  <div class="container">
    <div class="user-list">
      <h2>用户列表</h2>
      <ul>
        <li @click="enterChatRoom(user.roomNum)" v-for="(user, index) in userList" :key="user.userId"><el-avatar :src="user.avatarPath"></el-avatar>{{ user.username }}</li>
      </ul>
    </div>
    <div class="chat-container">
      <div class="message-container">
        <div v-for="(item, index) in messageList" :key="index"
          :class="['message', {'right': item.accountId == accountId, 'left': item.accountId != accountId}]">
          <div
            :class="{'messageAndImgRight': item.accountId !== accountId, 'messageAndImgLeft': item.accountId === accountId}">
            <span v-if="item.accountId != accountId"><el-avatar :src="item.userImg"></el-avatar></span>
            <span style="background-color:  #c7edfc;" class="message">{{ item.message }}</span> &nbsp;&nbsp;
            <span v-if="item.accountId == accountId"><el-avatar :src="item.userImg"
                style="width: 30px;height: 30px;"></el-avatar></span>
          </div>
        </div>
      </div>
      <div class="input-container">
        <input type="text" v-model="newMessage" placeholder="请输入你要发送的消息">
        <button @click="handleSendButton()">发送</button>
        <button @click="handleLogoutButton()">退出</button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
  export default {
    name: "WebSocket",
    data() {
      return {
        accountId: null, // 设置账号id
        userList: [], // 示例用户列表
        messageList: [],
        newMessage: '',
        roomNum:null,
      }
    },
    methods: {
      webSocketInit() {
        let token = localStorage.getItem("token");
        const webSocketUrl = 'ws://192.168.70.131:9001/message/webSocket/'+token+'/'+this.roomNum
        this.webSocketObject = new WebSocket(webSocketUrl);
        this.webSocketObject.onopen = this.webSocketOnOpen
        this.webSocketObject.onmessage = this.webSocketOnMessage
        this.webSocketObject.onerror = this.webSocketOnError
        this.webSocketObject.onclose = this.webSocketOnClose
      },
      webSocketOnOpen(e) {
        console.log('与服务端连接打开->', e)
      },
      webSocketOnMessage(e) {
        console.log('来自服务端的消息->', e)

        this.messageList.push(JSON.parse(e.data));
        console.log("__________________________")
        console.log("消息列表")
        console.log(this.messageList)
      },
      webSocketOnError(e) {
        console.log('与服务端连接异常->', e)
      },

      webSocketOnClose(e) {
        console.log('与服务端连接关闭->', e)
      },
      handleSendButton() {
        const message = this.newMessage
        this.webSocketObject.send(JSON.stringify({
          message, //消息数据
        }))
        this.newMessage = ''
      },
      handleLogoutButton() {
        this.username = null
        this.webSocketObject.close();
        this.$router.push({
          name: 'first'
        })
      },
      loadAllRoomNum(){
        axios.get("/message/allRoomnum/loadAllRoomNum").then(resp=>{
          console.log(resp)
          this.userList = resp.data.data
        })
      },
      enterChatRoom(roomNum){
        alert(roomNum)
        this.roomNum = roomNum
        this.webSocketInit()
      },


    },
    created() {
      this.loadAllRoomNum()
      //获取当前 用户的账号id
      this.accountId = localStorage.getItem("id");
    },
    //页面销毁时
    beforeDestroy() {
      this.username = null;
      if (this.webSocketObject) {
        this.webSocketObject.close();
      }
    }
  }
</script>

<style>
  .container {
    display: flex;
  }

  .user-list {
    width: 20%;
    height: 600px;
    border: 1px solid #ccc;
    padding: 10px;
    box-sizing: border-box;
  }

  .user-list h2 {
    margin: 0 0 10px 0;
  }

  .user-list ul {
    list-style-type: none;
    padding: 0;
  }

  .user-list li {
    padding: 5px 0;
    border-bottom: 1px solid #eee;
  }

  .chat-container {
    width: 60%;
    height: 600px;
    border: 1px solid #ccc;
    padding: 10px;
    box-sizing: border-box;
  }

  .message-container {
    overflow-y: auto;
    height: 80%;
  }

  .message {
    margin-bottom: 10px;
    padding: 10px;
    border-radius: 5px;
    clear: both;
  }

  .message.left {
    float: left;
  }

  .message.right {
    float: right;
  }

  .input-container {
    margin-top: 10px;
  }

  .input-container input {
    width: 55%;
    height: 40px;
    padding: 5px;
    box-sizing: border-box;
    border: 1px solid #ccc;
    border-radius: 4px;
  }

  .input-container button {
    padding: 5px 10px;
    margin-left: 5px;
    cursor: pointer;
    border: none;
    background-color: #007bff;
    color: white;
    border-radius: 4px;
  }

  .input-container button:hover {
    background-color: #0056b3;
  }

  .messageAndImgRight,
  .messageAndImgLeft {
    display: flex;
    flex-direction: row;
    align-items: center;
  }

  .messageAndImgLeft {
    justify-content: flex-start;
  }

  .messageAndImgRight {
    justify-content: flex-end;
  }
</style>
